import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:vamos/core/index.dart';
import '../../core/models/ranking_user_entity.dart';
import '../../core/models/user_model.dart';
import '../../core/models/leaderboard_comment_entity.dart';
import '../../core/di/service_locator.dart';
import '../../core/widgets/login_required_dialog.dart';
import '../../core/widgets/report_dialog.dart';
import '../../core/store/redux_leaderboard_manager.dart';
import '../../core/store/redux_user_manager.dart';

// 排行榜页面
class VamosRankingInterface extends StatefulWidget {
  const VamosRankingInterface({Key? key}) : super(key: key);

  @override
  State<VamosRankingInterface> createState() => _VamosRankingInterfaceState();
}

class _VamosRankingInterfaceState extends State<VamosRankingInterface>
    with WidgetsBindingObserver, RouteAware {
  final TextEditingController _commentController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 监听应用生命周期变化，当用户从其他页面返回时刷新状态
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    _commentController.dispose();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    // 当应用从后台返回前台时，刷新登录状态
    if (state == AppLifecycleState.resumed) {
      setState(() {});
    }
  }

  @override
  void didPopNext() {
    super.didPopNext();
    // 当从其他页面返回时，刷新登录状态
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Stack(
          children: [
            // 固定在顶部的图片
            Positioned(top: 0, left: 0, right: 0, child: _buildTopImage()),

            // 主要内容
            Column(
              children: [
                // 标题栏
                _buildTopBar(),

                // 可滚动内容
                Expanded(
                  child: SingleChildScrollView(child: _buildRankingList()),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 构建顶部栏
  Widget _buildTopBar() {
    return SafeArea(
      bottom: false,
      child: Container(
        height: 56.h,
        child: Row(
          children: [
            // 返回按钮
            Icon(Icons.arrow_back, size: 26.sp, color: Colors.white)
                .paddingHorizontal(16.w)
                .inkWell(
                  onTap: () {
                    Navigator.of(context).pop();
                  },
                ),

            // 标题
            Expanded(
              child: Text('Ranking')
                  .fontSize(16.sp)
                  .fontFamily(
                    GoogleFonts.goblinOne(
                      fontWeight: FontWeight.w400,
                    ).fontFamily,
                  )
                  .textColor(Colors.white)
                  .textAlignment(TextAlign.center),
            ),

            // 占位，保持对称
            SizedBox(width: 56.w),
          ],
        ),
      ),
    );
  }

  // 构建顶部图片
  Widget _buildTopImage() {
    return Container(
      width: double.infinity,
      child: Image.asset(
        'assets/images/rank_top.png',
        fit: BoxFit.fitWidth,
        errorBuilder: (context, error, stackTrace) {
          return Container(
            height: 200.h,
            color: Colors.grey[300],
            child:
                Icon(
                  Icons.image_not_supported,
                  size: 50.sp,
                  color: Colors.grey[600],
                ).center(),
          );
        },
      ),
    );
  }

  // 构建排行榜列表
  Widget _buildRankingList() {
    final rankings = leaderboardManager.getAllRankings();
    return Stack(
      children: [
        // 背景图片
        Image.asset('assets/images/rank_bg.png', fit: BoxFit.fitWidth),

        // 排行榜内容
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Column(
            children: [
              SizedBox(height: 130.h),
              // 前三名特殊布局
              _buildTopThreeRankings(rankings.take(3).toList()),

              SizedBox(height: 60.h),

              // 其余排名
              ListView.builder(
                padding: EdgeInsets.zero,
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemCount: rankings.skip(3).length,
                itemBuilder: (context, index) {
                  final ranking = rankings.skip(3).toList()[index];
                  final isLast = index == rankings.skip(3).length - 1;
                  return _buildRankingItem(ranking, isLast: isLast);
                },
              ),

              SizedBox(height: 60.h),

              // 评论列表
              _buildCommentList(),
            ],
          ),
        ),
      ],
    );
  }

  // 构建前三名特殊布局
  Widget _buildTopThreeRankings(List<RankingUserEntity> topThree) {
    if (topThree.isEmpty) return SizedBox.shrink();

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        // 第二名
        if (topThree.length > 1)
          Transform.translate(
            offset: Offset(0, 40.h), // 向下偏移20.h
            child: _buildTopRankingItem(topThree[1], 2),
          ),

        // 第一名
        if (topThree.isNotEmpty) _buildTopRankingItem(topThree[0], 1),

        // 第三名
        if (topThree.length > 2)
          Transform.translate(
            offset: Offset(0, 40.h), // 向下偏移20.h
            child: _buildTopRankingItem(topThree[2], 3),
          ),
      ],
    );
  }

  // 构建前三名单项
  Widget _buildTopRankingItem(RankingUserEntity ranking, int position) {
    final user = userManager.getUserById(ranking.userId);
    if (user == null) return SizedBox.shrink();

    return Container(
      width: 100.w,
      child: Column(
        children: [
          SizedBox(height: 8.h),

          // 排名
          Text('No.$position').fontSize(16.sp).bold().textColor(Colors.black),

          SizedBox(height: 8.h),

          // 用户头像
          _buildUserAvatar(user, 60.w),

          SizedBox(height: 8.h),

          // 用户名
          Text(user.displayName)
              .fontSize(12.sp)
              .textColor(Colors.black)
              .textAlignment(TextAlign.center),

          SizedBox(height: 4.h),

          // 点赞数
          _buildLikeCount(ranking.totalLikeCount),
        ],
      ),
    );
  }

  // 构建用户头像
  Widget _buildUserAvatar(UserDataEntity user, double size) {
    return Container(
      width: size,
      height: size,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        border: Border.all(color: Colors.white, width: 2),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: ClipOval(
        child: Image.asset(
          user.profileImage,
          width: size,
          height: size,
          fit: BoxFit.cover,
          errorBuilder: (context, error, stackTrace) {
            return Container(
              color: Colors.grey[300],
              child: Icon(
                Icons.person,
                size: size * 0.5,
                color: Colors.grey[600],
              ),
            );
          },
        ),
      ),
    );
  }

  // 构建点赞数
  Widget _buildLikeCount(int likeCount) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text('Number Of Likes')
            .fontSize(8.sp)
            .textColor(Colors.black87)
            .fontFamily(
              GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
            ),
        SizedBox(width: 4.w),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Image.asset(
              'assets/images/rank_like.png',
              width: 20.w,
              height: 20.w,
            ),
            SizedBox(width: 2.w),
            Text(likeCount.toString())
                .fontSize(16.sp)
                .italic()
                .fontFamily(
                  GoogleFonts.poppins(fontWeight: FontWeight.w700).fontFamily,
                )
                .textColor(Colors.black),
          ],
        ),
      ],
    );
  }

  // 构建排行榜单项
  Widget _buildRankingItem(RankingUserEntity ranking, {bool isLast = false}) {
    final user = userManager.getUserById(ranking.userId);
    if (user == null) return SizedBox.shrink();

    return Container(
      margin: EdgeInsets.only(
        left: 10.w,
        right: 8.w,
        top: 7.h,
        bottom: isLast ? 0.h : 7.h,
      ),
      padding: EdgeInsets.all(10.w),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment(-0.26, -0.98),
          end: Alignment(0.94, 1.98),
          colors: [const Color(0xFFCEF672), Colors.white],
        ),
        borderRadius: BorderRadius.circular(10.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 4,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          // 排名
          Text('No.${ranking.rankPosition}')
              .fontSize(16.sp)
              .textColor(Colors.black)
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily,
              ),

          SizedBox(width: 16.w),

          // 用户头像
          _buildUserAvatar(user, 40.w),

          SizedBox(width: 12.w),

          // 用户名
          Expanded(
            child: Text(
              user.displayName,
            ).fontSize(14.sp).textColor(Colors.black),
          ),

          // 点赞数
          _buildLikeCount(ranking.totalLikeCount),
        ],
      ),
    );
  }

  // 构建评论列表
  Widget _buildCommentList() {
    final comments = leaderboardManager.getCommentsSortedByTime();

    return ClipRRect(
      borderRadius: BorderRadius.circular(24.r),
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 50, sigmaY: 50),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.grey.withValues(alpha: 0.3),
            borderRadius: BorderRadius.circular(24.r),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 评论输入框
              Container(
                margin: EdgeInsets.only(top: 14.h, left: 16.w, right: 16.w),
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 0.h),
                decoration: BoxDecoration(
                  color: Colors.grey[200],
                  borderRadius: BorderRadius.circular(25.w),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: TextField(
                        controller: _commentController,
                        decoration: InputDecoration(
                          hintText: 'Input Content',
                          hintStyle: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 14.sp,
                          ),
                          border: InputBorder.none,
                          contentPadding: EdgeInsets.zero,
                        ),
                        style: TextStyle(color: Colors.black, fontSize: 14.sp),
                      ),
                    ),
                    SizedBox(width: 8.w),
                    Image.asset(
                      'assets/images/send.png',
                      width: 20.w,
                      height: 20.w,
                    ).inkWell(onTap: () => _handleSendComment()),
                  ],
                ),
              ),

              // 评论列表
              ...comments.map((comment) => _buildCommentItem(comment)),

              SizedBox(height: 20.h),
            ],
          ),
        ),
      ),
    );
  }

  // 构建评论项
  Widget _buildCommentItem(LeaderboardCommentEntity comment) {
    final user = userManager.getUserById(comment.authorId);
    if (user == null) return SizedBox.shrink();

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 0.w, vertical: 12.h),
      padding: EdgeInsets.symmetric(horizontal: 16.w),

      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户信息行
          Row(
            children: [
              // 用户头像
              _buildUserAvatar(user, 40.w),

              SizedBox(width: 12.w),

              // 用户名和状态
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      user.displayName,
                    ).fontSize(14.sp).bold().textColor(Colors.white),
                    SizedBox(height: 2.h),
                    Text(
                      user.personalBio,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ).fontSize(8.sp).textColor(Colors.white),
                  ],
                ),
              ),

              // 举报图标
              Image.asset(
                'assets/images/comment_report.png',
                width: 20.w,
                height: 20.w,
              ).inkWell(onTap: () => _handleReportComment(comment)),
            ],
          ),

          SizedBox(height: 12.h),

          // 评论内容
          Text(comment.content).fontSize(14.sp).textColor(Colors.white),
        ],
      ),
    );
  }

  /// 处理发送评论
  Future<void> _handleSendComment() async {
    final content = _commentController.text.trim();

    // 检查输入内容是否为空
    if (content.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Please enter some content'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // 检查用户是否已登录
    if (!_isUserLoggedIn()) {
      // 显示登录弹窗
      VamosLoginRequiredDialog.showLoginRequiredDialog(context);
      return;
    }

    // 用户已登录，发送评论
    await _sendComment(content);
  }

  /// 检查用户是否已登录
  bool _isUserLoggedIn() {
    final userManager = serviceLocator<ReduxUserManager>();
    return userManager.isUserLoggedIn();
  }

  /// 发送评论
  Future<void> _sendComment(String content) async {
    try {
      final leaderboardManager = serviceLocator<ReduxLeaderboardManager>();
      final userManager = serviceLocator<ReduxUserManager>();

      // 获取当前登录用户的ID
      final currentUser = userManager.getCurrentUser();
      if (currentUser == null) {
        throw Exception('User not logged in');
      }
      final currentUserId = currentUser.uniqueId;

      // 添加评论
      final newComment = LeaderboardCommentEntity(
        commentId: 'comment_${DateTime.now().millisecondsSinceEpoch}',
        authorId: currentUserId,
        content: content,
        commentTime: DateTime.now(),
      );

      await leaderboardManager.addComment(newComment);

      // 清空输入框
      _commentController.clear();

      // 显示成功提示
      NotificationUtils.showSuccess(
        context,
        message: 'Comment sent successfully!',
      );

      // 刷新页面
      setState(() {});
    } catch (e) {
      // 显示错误提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Failed to send comment. Please try again.'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// 处理举报评论
  void _handleReportComment(LeaderboardCommentEntity comment) {
    showVamosReportDialog(
      context: context,
      title: 'Report Comment',
      subtitle: 'Please select a reason for reporting this comment',
      onReportSubmitted: (VamosReportOption option) async {
        await _processReport(comment, option);
      },
    );
  }

  /// 处理举报提交
  Future<void> _processReport(
    LeaderboardCommentEntity comment,
    VamosReportOption option,
  ) async {
    try {
      final leaderboardManager = serviceLocator<ReduxLeaderboardManager>();

      // 删除被举报的评论
      final success = await leaderboardManager.removeComment(comment.commentId);

      if (success) {
        // 显示成功提示
        NotificationUtils.showSuccess(
          context,
          message: 'Comment reported successfully!',
        );

        // 刷新页面
        setState(() {});
      } else {
        // 显示错误提示
        NotificationUtils.showError(
          context,
          message: 'Failed to report comment. Please try again.',
        );
      }
    } catch (e) {
      // 显示错误提示
      NotificationUtils.showError(
        context,
        message: 'An error occurred while processing the report.',
      );
    }
  }
}
